// 图表模块
define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util  = require('util');
	var view  = require('@base/view');
	var chart = require('@base/chart');
	var grid = require('@base/grid');
	var date = require('@base/common/date');
	var drop = require('@base/common/drop');
	var echarts = require('@base/echarts');
	// var dateRange = require('@base/common/date');
	// var common = require('@base/common/base');

	var labels = require('modules/labels');
	format = labels.format;
	labels = labels.labels;


	// 活动图表
	var CampaignChart = chart.base.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"class":"M-chartAdv"

				// 数据接口
				,"url":"campaign/trend"
				,"param":{
					"ids":[],		// 活动id
					"metrics": [],	// 查询指标
					"viewtb": 0,	// 时间粒度
					"no_limit": true
				}
				,'reqType': 'websocket'

				// 时间粒度
				,"viewtb":0
				// 图表配置
				,"chart":{
					"height":270
					,"build":{
						"chart": {
							// 间距
							"margin":[30,20,60,70]
						}
						,"legend":{
							"borderWidth":0
						}
						,"plotOptions":{
							"series":{
								// 平时不显示数据点
								"marker":{
									"enabled":false
								}
							}
						}
					}
				}
				,"grid":1
				// 允许改变指标
				,"allowChangeIndex":true
				// 允许切换时间粒度
				,"allowChangeTimerange":true
				// 允许切换图表类型
				,"allowChangeType":false
				// 默认显示的指标
				// {text: LANG('展示量'),field: "impressions",label_field: 'trend_key'}
				,"defIndex":null
				// 支持的指标
				,"indexs":null
				// 图表类型
				,"type":"line"
				// 可添加的统计数据总量
				,"max":3
				// 折叠状态
				,"collapse":1
				// 是否已折叠
				,"hasCollapse":1
				// x轴要显示的字段
				,"label_field":"trend_key"
				// 图表x轴步长。
				,"xAxisSetp":6
				// 表格每页显示页数
				,"table_size":20
				// 是否显示标题
				,"hasTitle":true
				// 默认标题
				,"title":LANG("标题")
				// 是否有汇总
				,"hasTotal":true
				// 自动抓取数据
				,"autoLoad":true
				// 主判断键名
				,"key":"_id"
				// 请求conditions字段的配置
				// 当有多个要传递或传递的conditions与param中的type不同时使用
				// key代表condition，对应的值表示取数据中的某个字段
				// eg.{"user":"Id","status":"RunStatus"}
				,"conditions":null
				// 每个condition的后缀
				,"conditionSuffix":"_id"
				// 是否在参数中传递condition
				,"hasCondition":true
				,"tab": null // 指标分组配置
				,"overview": false // 是否查看汇总信息（get_all_info),图和表都要发这个参数
			});

			var c = config.get();

			// 图表里的设定是/2的
			c.xAxisSetp = Math.ceil(c.xAxisSetp/2);

			// 支持的指标
			this.$indexs = c.indexs;

			// 默认指标
			this.$defIndex = c.defIndex;

			// 当前指标
			this.$nowIndex = c.defIndex ;

			// 标签设定
			this.$labels = null;

			// 加载状态
			this.$loading = false;

			// 图表类型
			this.$type = c.type !== "advChart" ? c.type : "line";

			// 时间粒度
			this.$timeRange = c.viewtb;

			// 添加的趋势数量
			this.$serieNum = 0;
			this.$serieIndex = 0;

			// 当前模式:0图，表
			this.$mode = 1;

			// 当前页数
			this.$nowPage = 1;

			// 标题模板
			this.$titleTpl = "{date} {type}";

			// 标题上显示的时间
			this.$titleDate = "";

			// 条数关系
			this.$seriesNumMap = {};

			this.doms = {
				"index":null
				,"time":null
				,"collapse":null
				,"chart":null
				,"main":null
				,"refresh":null
				,"mode":null
			}

			this.$collapse = c.collapse;

			this.$first = true;

			// 活动ids
			this.$ids = [];

			this.initConfig(c);

			this.Super('init', arguments);

			// 数据
			this.$data = {};
		}
		/**
		 * 获取图表支持的指标相关设定
		 * @param  {Object} labels 表格指标设定模块
		 * @return {Object}        模块实例
		 */
		,initConfig:function(c){
			this.$labels = labels && labels.config || {};

			// 若没设置指标数据，则取指标分组中的并集为指标
			if(!c.indexs ){
				var metrics = [];
				var group = c.tab || pubjs.config("defaultGroup");
				for(var n in group){
					if(group[n] && group[n].cols){
						metrics = metrics.concat(group[n].cols);
					}
				}
				this.$indexs = metrics;
			}

			// 若没设置默认指标，则以首指标为默认指标
			if(!c.defIndex){
				var name = this.$indexs[0];
				this.$nowIndex = labels.get(name);
				this.$nowIndex.field = name;
				this.$nowIndex.label_field = c.label_field;
			}

			// 更新请求参数param
			c.param.metrics = [this.$nowIndex.field];
			c.param.viewtb = this.$timeRange;

			return this;
		}
		,afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.$el.getDOM();

			self.doms.main = $('<div class="M-chartAdvMain"></div>').appendTo(el);

			// 折叠功能
			if(c.hasCollapse){
				self.doms.collapse = $([
					'<div class="M-chartAdvCollapse">',
						'<div>',
							'<p data-close="0">',
								'<em class="triangle-top"></em>',
								'<b></b>',
								'<span></span>',
								'<i></i>',
							'</p>',
						'</div>',
					'</div>'
				].join('')).appendTo(el);
				self.doms.collapseBtn = self.doms.collapse.find("p:first");
				// self.toggleChart(!self.$collapse, true, true);
				self.jq(self.doms.collapseBtn,"click mouseenter mouseleave","eventToggleTrend");
			}else{
				self.buildChart(function() {
					self.load();
				});
			}

			return this;
		}
		,buildChart: function(callback){
			var conf = this.getConfig();
			var that = this;
			var cb = function() {
				that.switchMode(that.$mode);
				if (callback) {
					callback.call(that);
				}
			}

			if (this.$chartIsBuilded) {
				cb();
				return this;
			}
			this.$chartIsBuilded = true;

			this.toggleLoading(true);



			// 图表切换
			if(conf.grid){
				this.doms.mode = $('<div class="M-chartAdvModeBox"></div>').appendTo(this.doms.main);
				this.createDelay(
					"mode"
					,'@base/common/input.buttonGroup'
					,{
						"items":[LANG("图"),LANG("表")]
						,"target":this.doms.mode
						,"selected":this.$mode
					}
				);
			}

			// 指标多级下拉框
			// @todo 支持单级下拉框
			if(conf.allowChangeIndex){
				this.doms.index = $('<div class="M-chartAdvIndexBox"></div>').appendTo(this.doms.main);
				var tabConfig = conf.tab || pubjs.config('defaultGroup');
				this.createDelay(
					"index"
					,'@base/common/dropdown.subDropdown'
					,{
						"target":this.doms.index
						,"width":140
						,"options": this._formatMetrics(tabConfig)
						,"def":this.$nowIndex.text
						,"search": false
						,"drag":false
						,"canSelectParent": false
					}
				);
			}

			// 刷新按钮
			this.doms.refresh = $([
				'<div class="M-chartAdvRefreshBox">',
					'<button title="'+LANG('刷新')+'" class="refNormal">',
						'<i class="uk-icon-rotate-right"/>',
					'</button>',
				'</div>'
				].join('')).appendTo(this.doms.main);
			this.doms.refresh = this.doms.refresh.find("button:first");
			this.jq(this.doms.refresh,"click","eventRefreshClick");

			// 时间粒度
			if(conf.allowChangeTimerange){
				this.doms.time = $('<div class="M-chartAdvTimeBox"></div>').appendTo(this.doms.main);
				this.createDelay(
					"time"
					,'@base/common/input.timeRange'
					,{
						"target":this.doms.time
						,"selected":this.$timeRange
						,'items': [LANG('小时'), LANG('天'), LANG('周'),LANG('月')]
					}
				);
			}

			// 标题
			if(conf.hasTitle){
				// conf.title = conf.title && conf.title+" "+this.$nowIndex.text || this.$nowIndex.text;
				conf.title = conf.title && conf.title+" "+(this.$nowIndex&&this.$nowIndex.text||'');
				this.doms.title = $('<div class="M-chartAdvTitleBox">'+conf.title+'</div>').appendTo(this.doms.main);
			}

			// 设定图表添加区域
			this.doms.chart = $('<div class="M-chartAdvChart"></div>').appendTo(this.doms.main);
			// 完成配置
			conf.chart.target = this.doms.chart;
			if(conf.hasTotal){
				// 有汇总
				var series = $.extend({},this.$nowIndex);
				series.text = series.text + LANG("汇总");
				series.label_field = conf.label_field;
				series.y_field = 'm_' + (this.$serieIndex++);
				// 首条，第0条
				conf.chart.series = [series];
				this.$serieNum++;
			}else{
				conf.chart.series = [];
			}
			conf.chart.width = conf.chart.width || this.$el.getDOM().width();

			this.create("chart", chart[this.$type], conf.chart);
			this.$chart = this.$.chart.getChart();

			// 表格
			if(conf.grid){
				this.doms.grid = $('<div class="M-chartAdvGrid"></div>').appendTo(this.doms.main);
				// var chartHeight = util.getViewport().height*0.6;
				// this.doms.grid.css('height',600);
				this.createDelay("grid", '@base/highGrid.base',{
					target: this.doms.grid,
					url: conf.url,
					param: {
						viewtb: this.$timeRange,
						get_all_info: conf.overview ? 1 : 0,
						no_limit: true
					},
					auto_load:false,
					cols: [
						{type:"id"},
						{name:'trend_key',text: LANG('时间')}
					],
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost",
						"win_rate"
					],
					hasPager: false,
					hasAmount: false,
					hasSubGrid: false,
					hasRefresh: false,
					reqType: 'websocket',
					gridName: 'period',
					wrapperClass: 'M-chartAdvGrid',
					formatData: function(data){
						return {'items': data && data.amount};
					},
					'hasSearch': false,
					'hasFilter': false
				});
			}

			this.createDelay(true, function() {
				that.toggleLoading(false);
				cb();
			});

			return this;
		}
		,resetChart: function(){
			var c = this.getConfig();
			// 清除DOM元素
			this.doms.main.empty();

			// 清除实例
			this.$.chart.destroy();

			// 图表切换
			if(c.grid){
				this.$.mode.destroy();
			}
			// 指标多级下拉框
			if(c.allowChangeIndex){
				this.$.index.destroy();
			}
			// 时间粒度
			if(c.allowChangeTimerange){
				this.$.time.destroy();
			}
			// 表格
			if(c.grid){
				this.$.grid.destroy();
			}
		}
		,getDOM: function(){
			return this.$el.find('.M-chartAdvMain');
		}
		// 绘图
		,toggleDraw: function(id){
			var index = util.index(this.$ids, id);
			if(index == null){
				this.$ids.push(id);
			}else{
				this.$ids.splice(index, 1);
			}
			// 如果趋势图已打开才绘图
			var el = this.getDOM();
			if(el.is(':visible') && el.width() && el.height()){
				this.load();
			}
		}
		,load:function(param){

			var c = this.getConfig();

			//按需更新时间请求参数，如果有传时间参数，就用传进来参数，没有的话，使用默认的时间
			var date = pubjs.getDate();
			param = util.extend(date, param);

			if(param){
				this.setParam(param);
			}

			// 图
			if( this.$mode === 0){
				this.toggleLoading(true);

				var trendParam = this.getParam();

				switch(c.reqType){
					case 'ajax':
						pubjs.data.get(c.url, trendParam, this);
					break;
					case 'websocket':
						pubjs.mc.send(c.url, trendParam, this.onData.bind(this));
					break;
				}
				return;
			}

			// 表
			if( this.$mode === 1){
				if (this.$.grid) {
					this.$.grid.reload(param);
				}
				return;
			}
		}
		,onData:function(err, data){
			this.toggleLoading(false);

			if(err){
				pubjs.alert(err.message);
				// this.setData();
				return false;
			}
			this.setData(data);

			this.toggleRefreshStatus(false);
		}
		,getData:function(){
			return this.$data;
		}
		,setData:function(data){
			var i;
			var c = this.getConfig();

			// 更新config.series
			var series = [
				{						// 汇总数据
					"id": 'amount',
					"text": this.$nowIndex.text + LANG('汇总'),
					"y_field": 'm_amount',
					"label_field":c.label_field
				}
			];
			var desc = data.desc;
			for(i in desc){
				series.push({			// 单条数据
					"id": i,
					"text": desc[i],
					"y_field": 'm_' + i,
					"label_field":c.label_field
				});
			}
			this.$.chart.setConfig('series', series);

			// 更新$data
			this.$data = {
				'amount': data.amount	// 汇总数据
			};
			var items = data.items;		// 单条数据
			for(i in items){
				this.$data[i] = items[i];
			}

			// 首次画图才要初始化
			if(this.$first){
				this.$first = false;
				this.setChartSetp();
			}

			// 表格
			if(this.$mode){
				if(this.$timeRange){
					this.$.pager.show();
					this.$.pager.setup({
						"total":this.$data['amount'].length
					});
				}
				this.$.grid.setData(
					this.buildGridData(this.$nowPage)
				);
			}
			// 趋势图
			else{
				this.$.chart.setData(
					this.formatChartData()
				);
			}
			// 汇总操作
			if(c.hasTotal){
				this.toggleSeries(0, series.length<=1);
			}

			return this;
		}
		,reset:function(){
			var c = this.getConfig();

			this.$nowIndex = this.$defIndex;
			this.$timeRange = c.viewtb;
			this.$mode = 0;
			this.$.mode.setData(this.$mode);
			this.$data = {};
			this.$loading = false;
			this.$serieNum = 0;
			if(c.hasTitle){
				this.changeTitle("");
			}
			if(c.allowChangeIndex){
				this.$.index.reset();
			}
			if(c.allowChangeTimerange){
				this.$.time.reset();
			}
			if(c.allowChangeType){
				// 图表类型
			}
			this.$.chart.reset();
		}
		,setParam:function(param,replace){
			var c = this.getConfig();
			if(param){
				if(replace){
					c.param = param;
				}else {
					$.extend(c.param, param);
				}
			}
			return this;
		}
		,getParam: function(){
			var c = this.getConfig();
			var param = c.param;
			param.ids = this.$ids;

			var date = pubjs.getDate();
			param.begindate = date.begindate;
			param.enddate = date.enddate;

			return param;
		}

		// 获取表格数据
		,buildGridData:function(){
			var c = this.getConfig();
			var list = [];
			var data = this.$data['amount'];

			for(var i = 0,l = (data && data.length || 0);i<l;i++){
				if(!this.$timeRange || i < c.table_size){
					list.push(data[i]);
				}else{
					break;
				}
			}
			data = null;
			return {'items': list};
		}
		,formatChartData: function(){
			var self = this;
			var c = self.getConfig();

			var key = self.$nowIndex.field;	// 指标
			var labels = self.$labels;
			var formater = labels[key] && util.isFunc(labels[key].format) && labels[key].format || null;

			var data = [];
			var label_key = c.label_field;	// 'trend_key'
			var seriesConfig = self.$.chart.getConfig('series');
			util.each(self.$data, function(value, idx){
				var serie = util.find(seriesConfig, idx, 'id');

				if ( serie == null) {
					return;
				}

				var filed = serie.y_field;
				util.each(value, function(node, idx){
					var item = data[idx];
					if (!item){
						item =  data[idx] = {};
						item[label_key] = node[label_key];
					}
					data[idx][filed] = self._getKeyData(node,key,formater);	//node[key];
				});
			});

			return data;
			/**
				old:[{
					m_0: 2154,
					m_1: 2117,
					trend_key: "00:00 ~ 00:59"
				}]
				new:[{
					m_amount: 2154,
					m_123: 2117,
					trend_key: "00:00 ~ 00:59"
				}]
			**/
		}
		/**
		 * 设置图表X轴的显示步长
		 * @return {Object} 模块实例
		 */
		,setChartSetp:function(){
			var c = this.getConfig();
			var _max = this.$data['amount'].length
				,oldSetp = this.$chart.xAxis[0].userOptions.labels.step
				,newSetp;
			if(_max <= c.xAxisSetp){
				newSetp = 1;
			}else{
				newSetp = Math.ceil(_max/(c.xAxisSetp*2));
			}
			if(newSetp !== oldSetp){
				this.$chart.xAxis[0].userOptions.labels.step = newSetp;
				this.$chart.xAxis[0].options.labels.step = newSetp;
			}
			newSetp = _max = oldSetp = null;
			return this;
		}
		// 修改标题
		,changeTitle:function(title){
			var c = this.getConfig();
			if(c.hasTitle && this.doms.title){
				if(util.isObject(title)){
					title = this.getTitleText(title);
				}else if(!title){
					title = this.getTitleText();
				}
				this.doms.title.text(title);
			}
			return this;
		}
		// 切换显示图表，表格
		,switchMode:function(mode){
			var c = this.getConfig();
			if(mode !== undefined){
				this.$mode = parseInt(mode,10);
			}
			this.doms.chart.toggle(this.$mode === 0);
			this.doms.grid.toggle(this.$mode === 1);
			if(c.allowChangeIndex){
				this.$.index[this.$mode ? "hide" : "show"]();
			}
			if(this.$mode){
				this.$.grid.reload();
			}else{
				this.load();
			}
			return this;
		}
		// 切换刷新按钮状态
		,toggleRefreshStatus:function(status){
			this.doms.refresh.toggleClass('is-disabled', status)
		}
		/**
		 * 修改显示的指标
		 * @param  {Object} param 切换到相关数据
		 * @return {Object}       实例对象
		 */
		,changeIndex:function(param){
			if(!param){
				return;
			}
			var c = this.getConfig();

			// 多级下拉框
			var isMultilevel = util.isArray(param.id);
			if(isMultilevel){
				param.id = param.id[param.id.length-1];
				param.option = param.option[param.option.length-1];
			}

			param.last = param.last || this.$nowIndex.field;
			this.$nowIndex = param.option;
			this.$nowIndex.field = param.id;
			var value = this.$labels[this.$nowIndex.field];
			this.$nowIndex.text = value &&value.text || this.$nowIndex.Name;

			if(c.hasTotal){
				// this.$nowIndex.text += LANG("汇总");
				this.$.chart.setSeries(0, this.$nowIndex);
			}

			this.changeTitle();
			if(!this.$collapse){
				this.load({
					metrics: [this.$nowIndex.field]
				});
			}

			return this;
		}
		/**
		 * 获取标准的标题文本
		 * @param  {Object} item 标题要用到的数据对象
		 * @return {String}      标题文本
		 */
		,getTitleText:function(item){
			if(item){
				if(item.text){
					item = item.text;
				}else{
					// item = item.nowDate;
					item = item.begin+"--"+item.end;
				}
				this.$titleDate = item;
			}
			return this.$titleTpl.replace('{date}',this.$titleDate).replace('{type}',this.$nowIndex.text);
		}
		/**
		 * 更新时间段参数
		 * @param {Object} date datebar模块返回的时间段参数
		 * @return {Bool}		返回是否有参数更新
		 */
		,setDateRange:function(date){
			var c = this.getConfig();
			var param = {};
			if (date.stastic_all_time){
				param = {
					"stastic_all_time":1
					,"begindate":null
					,"enddate":null
				};
			}else {
				param = {
					"stastic_all_time":null
					,"begindate":date.begindate
					,"enddate":date.enddate
				};
			}
			// 时间粒度
			this.$timeRange = this.$.time.updateState(param);
			c.param.viewtb = this.$timeRange;
			c.param.begindate = date.begindate;
			c.param.enddate = date.enddate;
			return param;
		}
		/**
		 * 切换显示单条
		 * @param  {Number}      index 显示状态
		 * @param  {Bool}        show  显示状态
		 * @return {Undefined}         无返回值
		 */
		,toggleSeries:function(index,state){
			this.$.chart.toggleSeries(index,state);
		}
		/**
		 * 获取Condition
		 * @param  {Object} data 数据对象
		 * @return {String}      Condition字符串
		 */
		,getConditions:function(data){
			var conditions = []
				,conf = this.getConfig()
				,suffix = conf.conditionSuffix+"|";
			if(conf.conditions){
				conf = conf.conditions;
				for(var n in conf){
					conditions.push(
						n+suffix+data[conf[n]]
					);
				}
			}else{
				if(conf.param.type){
					conditions.push(conf.param.type+suffix+data[conf.key]);
				}
			}
			conf = suffix = null;
			return conditions.toString();
		}
		/**
		 * 添加一条趋势
		 * @param  {Object} data  要添加的趋势对应的数据
		 * @param  {Object} param 附加参数
		 * @return {Bool}         添加结果
		 */
		,addSeries:function(data,param){
			var c = this.getConfig();
			var key = data && data[c.key];

			if(key){
				var num = this.$serieNum;
				var max = c.max;
				if (c.hasTotal){
					max++;
				}
				if(num < max){
					this.$seriesNumMap[key] = num;
					var conf = {
						"text":data.Name
						,"y_field": 'm_' + (this.$serieIndex++)
						,"label_field":c.label_field
						,"id":key
					}
					this.$.chart.config.series.push(conf);
					this.$chart.addSeries(conf);
					param = param || {};
					if(c.hasCondition){
						param.condition =this.getConditions(data);
					}
					this.$serieNum++;
					this.$param[num] = param;
					// 图表已打开, 加载当前数据
					if (!this.$collapse){
						this.load();
					}
					return true;
				}else{
					pubjs.alert(LANG("最多只能添加%1条对比数据",c.max));
				}
			}
			return false;
		}
		/**
		 * 删除一条趋势
		 * @param  {Mix}    data 要删除的趋势对应的索引或数据
		 * @return {Bool}        删除结果
		 */
		,removeSeries:function(data){
			var c = this.getConfig();
			var key = data[c.key]
				,map = this.$seriesNumMap
				,num = this.$serieNum--
				,index = isNaN(data) ? map[key] : data;

			if(this.$chart.series[index]){
				// 删除chart配置
				this.$chart.series[index].remove();
				this.$.chart.config.series.splice(index,1);

				// 修正id map数据
				util.each(map, function(id){
					if (id == index){
						return null;
					}else if (id > index){
						return id-1;
					}
				});

				// 删除数据
				data = this.$data;
				for (;index<num;){
					data[index] = data[++index];
					data[index] = null;
				}

				if(num == 2){
					this.toggleSeries(0,true);
				}
				return true;
			}
			return false;
		}
		/**
		 * 检测某个id的数据是否已经添加
		 * @param  {Number}  id 数据id
		 * @return {Boolean}    true为已添加
		 */
		,hasAdded:function(id){
			return this.$seriesNumMap[id] === undefined ? false : true;
		}
		/**
		 * 切换图表的显示状态
		 * @param  {Bool}   show   显示状态
		 * @param  {Bool}   reload 重新加载
		 * @param  {Bool}   first  是否是首次调用，
		 * @return {Object}        模块实例
		 */
		,toggleChart:function(show, reload, first){
			if (show == null){
				show = this.$collapse;
				this.$collapse = !this.$collapse;
			}else {
				this.$collapse = !show;
			}

			this.doms.collapse.toggleClass("M-chartAdvCollapseClose", show)
				.find('em').toggleClass('triangle-bottom');
			this.doms.main[show ? "show" : "hide"]();

			if(show){
				var that = this;
				this.buildChart(function() {
					if (!!reload) {
						that.load();
					}
				});

				// 更新标题-日期
				var date = pubjs.getDate();
				this.changeTitle({
					begin: util.date('Y-m-d',date.begindate),
					end: util.date('Y-m-d',date.enddate)
				});
			}

			// 发图表显隐事件,让grid重新计算宽高
			if(!(first && !show)){
				this.fire('chartToggle');
			}

			return this;
		}
		/**
		 * 切换显示图表空白提示
		 * @param  {Bool}      show 显示状态
		 * @return {Undefined}      无返回值
		 */
		,toggleEmpty:function(show){
			this.$.chart.toggleEmpty(show);
		}
		/**
		 * 切换加载遮罩显示状态
		 * @param  {Bool}   status 显示状态
		 * @return {Object}        模块实例
		 */
		,toggleLoading:function(status){
			// if(status){
			// 	this.showLoading();
			// }else{
			// 	this.hideLoading();
			// }
			return this;
		}

		// 折叠按钮点击事件
		,eventToggleTrend:function(ev){
			if(ev.type === "click"){
				// 切换状态
				this.toggleChart(null, true);
			}else{
				// 鼠标经过样式
				this.doms.collapse[
					ev.type === "mouseenter" && "addClass" || "removeClass"
				]("actCol");
			}
			return false;
		}
		// 刷新按钮点击事件
		,eventRefreshClick:function(ev){
			this.load();
			return false;
		}

		// 按钮组切换响应事件 -图表
		,onChangeButton: function(ev){
			this.switchMode(ev.param.selected);
			return false;
		}
		// 下拉框切换响应事件 -指标
		,onOptionChange:function(ev){
			this.changeIndex(ev.param);
			return false;
		}
		// 时间粒度切换的响应事件
		,onChangeTimeRange:function(ev){
			this.$timeRange = +ev.param.selected || 0;
			var param = {"viewtb": this.$timeRange};
			this.$.grid.setParam(param);
			this.load(param);
			return false;
		}
		// 表格分页切换响应事件
		,onChangePage: function(ev){
			var c = this.getConfig();
			var size = c.table_size
				,data = this.$data[0]
				,idx = (ev.param - 1) * size
				,last = Math.min(data.length, idx + size)
				,list = [];
			for(;idx<last; idx++){
				list.push(data[idx]);
			}
			this.$.grid.setData(list);
			size = data = idx = last = list = null;
			return false;
		}
		// 响应日期条事件
		,onDateRangeChange: function(ev){
			// 更新标题-日期
			var date = pubjs.getDate();
			this.changeTitle({
				begin: util.date('Y-m-d',date.begindate),
				end: util.date('Y-m-d',date.enddate)
			});
			// pubjs.checkDisplay(this, ev.type, this.load.bind(this));
			return false;
		}

		// 生成下拉菜单能识别的数据格式
		,_formatMetrics: function(data){
			/**	选项格式
			[{
				_id:'front',
				Name: '前端',
				subs:[{
					_id: 'impressions',
					Name: '展示量'
				},{
					_id: 'rate',
					Name: '点击率'
				}]
			}]**/
			var options = [];
			for(var e in data){
				var group = {
					'_id': e,
					'Name': data[e].text,
					'subs': []
				}
				var cols = data[e].cols;
				for (var i = 0; i < cols.length; i++) {
					group.subs.push({
						'_id': cols[i],
						'Name': labels.get(cols[i]).text
					});
				}
				options.push(group);
			}

			return options;
		}
		/**
		 * 获取指定字段的数据
		 * @param  {Object}   data     数据对象
		 * @param  {String}   key      字段名
		 * @param  {Function} formater 格式化函数
		 * @return {Number}            获取的数据
		 * @private
		 */
		,_getKeyData:function(data,key,formater){
			data = data && data[key] || 0;
			if(data && formater){
				data = formater(data);
			}
			formater = null;
			data = this._getNumberData(data);
			return data;
		}
		/**
		 * 将格式化后的数据转回图表能用的数字
		 * @param  {String} data 要处理的数据字符串
		 * @return {Number}      处理完的数据(处理过程中如果NaN则会当成0)
		 * @private
		 */
		,_getNumberData:function(data){
			data = ""+data;
			data = data.replace(/[^0-9\.]/g,"");
			data = parseFloat(data);
			data = isNaN(data)?0:data;
			return data;
		}
	});
	exports.campaign = CampaignChart;

	// 时段图表 -todo子表格；而且代理和汇总下不同。
	var PeriodChart = view.container.extend({
		init:function(config){

			// 汇总子表格
			var overview_subgrid = config.param && config.param.overview_subgrid;
			this.$overview_subgrid = this.$overview_subgrid || {};
			if(overview_subgrid)
			{
				this.$overview_subgrid = {
					'get_all_info': 1,
					'ListAll':1,
					'showChildren':1,
					'overview_subgrid':1
				}
			}

			config = pubjs.conf(config, {
				"class":"M-chartAdv M-chartAdvMain"
				// 图表类型
				,"type":"line"
				// x轴要显示的字段
				,"label_field":"trend_key"
				// 图表x轴步长。
				,"xAxisSetp":6
				// 表格每页显示页数
				,"table_size":20
				// 数据接口
				,"url":"trend/period"
				,"param":util.extend(
					{
						"metrics": [		// 查询指标 9个
							'impressions',
							'clicks',
							'back_regs',
							'click_rate',
							'back_reg_rate',
							'avg_reg_cost',
							'cpm',
							'avg_click_cost',
							'back_reach_cost'
						],
						"viewtb": 0,		// 时间粒度
						"no_limit": true
					},
					this.$overview_subgrid,
					pubjs.getDate()
				)
				,'reqType': 'websocket'

				// 图表配置
				,"chart":{
					// 'height': 600,
					'build': {
						xAxis: {
							labels: {
								step:1,
								rotation: -25,
								align: 'right'
							}
						},
						yAxis: [
							{opposite: false, min:0},
							{opposite: false, min:0, title:{text:LANG('展示量 / 点击量 / 注册量')}},
							{opposite: true, min:0},
							{opposite: true, min:0, title:{text:LANG('比率(%) / 价格(RMB)')}}
						]
					},
					'series':[
						{y_field:'impressions', label_field:'trend_key', text:LANG('展示量'), y_axis:0},
						{y_field:'clicks', label_field:'trend_key', text:LANG('点击量'), y_axis:1},
						{y_field:'back_regs', label_field:'trend_key', text:LANG('注册量'), y_axis:1},
						{y_field:'click_rate', label_field:'trend_key', text:LANG('点击率(%)'), y_axis:2, y_format:this.formatRate},
						{y_field:'back_reg_rate', label_field:'trend_key', text:LANG('注册率(%)'), y_axis:2, y_format:this.formatRate},
						{y_field:'avg_reg_cost', label_field:'trend_key', text:LANG('注册单价'), y_axis:3, y_format:this.formatCurrency},
						{y_field:'cpm', label_field:'trend_key', text:LANG('CPM单价'), y_axis:3, y_format:this.formatCurrency},
						{y_field:'avg_click_cost', label_field:'trend_key', text:LANG('点击单价'), y_axis:3, y_format:this.formatCurrency},
						{y_field:'back_reach_cost', label_field:'trend_key', text:LANG('到达单价'), y_axis:3, y_format:this.formatCurrency}
					]
				}
				,'gridName': 'period'
				,'tab': {
					"front": true,
					"back": true,
					"conversion": true,
					"cost": true,
					"bid":{
						"text":LANG('竞价'),
						"cols":[
							"bid_num"				// 出价数
							,"win_num"				// 竞得数
							,"win_rate"				// 竞得率
							,"bid_use_rate"			// 使用率
						]
					}
				}
			});

			// 如果父级为落地页，指标组中要去掉前端类的指标
			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'cost': null, 'front': null}
				});
			}


			this.$data = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var c = this.getConfig();

			this.append([
				// 日期控件
				'<div class="M-chartAdvDateBox" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				// 图表切换
				'<div class="M-chartAdvModeBox clear" pub-name="mode" pub-mod="@base/common/input.buttonGroup" />',
				// 刷新按钮
				'<div class="M-chartAdvRefreshBox">',
					'<button title="'+LANG('刷新')+'" class="refNormal">',
						'<i class="uk-icon-rotate-right"/>',
					'</button>',
				'</div>',
				// 时间粒度
				'<div class="M-chartAdvTimeBox" pub-name="time" pub-mod="@base/common/input.timeRange" />',
				// 趋势图
				'<div class="M-chartAdvChart pt30" pub-name="chart" pub-mod="@base/chart.line" />',
				// 表格
				'<div class="M-chartAdvGrid" pub-name="grid" pub-mod="@base/highGrid.base" />'
			].join(''));

			// 绑定按钮事件
			this.jq(this.$el.find('.M-chartAdvRefreshBox button'), "click", "eventRefreshClick");

			// 重新处理列表参数
			var gridParam = util.extend(
				{}
				// ,c.param
				,c.syncParentGridParam ? c.param : {} // 需要同步的时候同步父表格
				,c.gridParam
				,{
					viewtb: 0,
					condition: c.param.condition
				}
				,this.$overview_subgrid
				,{metrics: []}
			);
			// 汇总的删除默认指标
			if(c.syncParentGridParam){
				delete gridParam.metrics;
			}


			var config = {
				'mode': {
					"selected": 1, // 0 图，1 表
					"items":[LANG("图"),LANG("表")]
				},
				'time': {
					"selected": 0,
					'items': [LANG('小时'), LANG('天'), LANG('周'),LANG('月')]
				},
				'chart': $.extend({width: this.$el.width()}, c.chart),
				'grid': {
					'url': c.url,
					'param': gridParam,
					'auto_load': false,
					'cols': [
						{type:"id"},
						{name:'hour',text: LANG('时间'), width:200, render:this.renderName, align:'center'}	// 小时
						// {name:'date',text: LANG('时间'), width:200, render:this.renderName, align:'center'},	// 天
						// {name:'week',text: LANG('时间'), width:200, render:this.renderName, align:'center'},	// 周
						// {name:'month',text: LANG('时间'), width:200, render:this.renderName, align:'center'}		// 月
					],
					'default_metrics' : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost",
						"win_rate"
					],
					'tab': c.tab,
					'eventDataLoad': true,
					'subgrid_title_field': 'trend_key',
					'key': "hour",
					'subField': "hour",
					'hasPager': true,
					'hasSubGrid': true,
					'hasRefresh': false,
					'reqType': 'websocket',
					'gridName': c.gridName || 'period',
					'gridNameSuffix': c.gridName ? c.gridNameSuffix : '',
					'hasSearch': false,
					'hasFilter': false,
					'hasDateRange': false
					// wrapperClass: 'G-frameBodyContainer'
				},
				'date': {
					'pos': 'bR',
					'broadcast': false
				}
			};

			this.buildFromTemplate(config);
		},
		onGridDataLoad: function(){
			// 隐藏全部列
			// this.$.grid.toggleColumn(['hour','date','week','month'], false);
			// this.toggleColumn();
		},
		toggleColumn: function(){
			var viewtb = this.$timeRange||0;
			var mapping = ['hour','date','week','month'];
			var name = mapping[viewtb];
			// 显示当条列
			this.$.grid.toggleColumn(name, true);
		},
		renderName: function(i, val, data, con){
			var text = data['trend_key'];
			var dom = $('<div class="fl uk-text-truncate" title="'+text+'"/>').text(text).width(con.width);
			return dom;
		},
		afterBuildTemplate: function(){
			var self = this;
			var c = self.getConfig();
			if(self.$.time){
				self.$.time.setDateRange(c.param);
			}
			// self.load();
		},
		load:function(param){
			var c = this.getConfig();

			var type = +this.$.mode.getData();
			var el = this.getDOM();
			el.find('.M-chartAdvChart').toggle(type === 0);
			el.find('.M-chartAdvGrid').toggle(type === 1);

			if(param){
				this.setConfig('param', $.extend(c.param, param));
			}

			// 图
			if(type === 0){
				this.toggleLoading(true);

				switch(c.reqType){
					case 'ajax':
						pubjs.data.get(c.url, c.param, this);
					break;
					case 'websocket':
						pubjs.mc.send(c.url, c.param, this.onData.bind(this));
					break;
				}
				return;
			}

			// 表
			// if(type === 1){
			// 	this.$.grid.reload(param);
			// 	return;
			// }
		},
		// 响应日期条事件
		onDateRangeChange: function(ev){
			if(!this.getDOM().is(':visible')){
				return false;
			}
			// 设置日期参数
			var param = ev.param.nowTimestamp;
			this.$.grid.setParam(param);
			this.$.chart.setParam(param);
			this.$.time.setDateRange(param);
			// this.load();

			return false;
		},
		onSubgridParam: function(ev){
			var self = this;
			var c = self.getConfig();
			// 汇总子表格时，需要同步更新
			if(c.syncParentGridParam){
				var param = ev.param.data;
				self.$.grid.setParam(param);
				self.$.chart.setParam(param);
				// self.load();	// 暂时不自动加载，只设参数，需要手动重新load
			}
		},
		onData:function(err, data){
			this.toggleLoading(false);

			if(err){
				pubjs.alert(err.message);
				return false;
			}

			this.setData(data);
		},
		setData:function(data){
			// 更新$data
			this.$data = data.items;

			var type = +this.$.mode.getData();

			// 趋势图
			if(type === 0){
				var chart = this.$.chart;
				chart.setData(this.$data);
				chart.toggleSeries(0, true);
				chart.toggleSeries(1, true);
				chart.toggleSeries(2, true);
				chart.toggleSeries(3, false);
				chart.toggleSeries(4, false);
				chart.toggleSeries(5, false);
				chart.toggleSeries(6, false);
				chart.toggleSeries(7, false);
				chart.toggleSeries(8, false);
				return;
			}

			// 表格
			if(type === 1){
				this.$.grid.setData(this.$data);
				return;
			}
		},
		// 刷新按钮点击事件
		eventRefreshClick:function(ev){
			this.load();
			return false;
		},
		// 图表切换
		onChangeButton: function(ev){
			var mode = +ev.param.selected || +this.$.mode.getData();

			var el = this.$el;
			el.find('.M-chartAdvChart').toggle(mode === 0);
			el.find('.M-chartAdvGrid').toggle(mode === 1);

			if(mode === 0){
				this.load();
			}

			if(mode === 1){
				this.$.grid.reload();
			}

			return false;
		},
		// 时间粒度切换
		onChangeTimeRange:function(ev){
			var viewtb = this.$timeRange = +ev.param.selected || 0;
			var param = {"viewtb": this.$timeRange};

			var mapping = ['hour', 'date', 'week', 'month'];

			// 更新key, subField
			var mod = this.$.grid;
			mod.setConfig('key', mapping[viewtb]);
			mod.setConfig('subField', mapping[viewtb]);

			mod.setParam(param);
			this.load(param);
			return false;
		},
		getData:function(){
			return this.$data;
		},
		reset:function(){
			this.$.mode.setData(0);
			this.$data = {};
			this.$.time.reset();
			this.$.chart.reset();
		},
		toggleEmpty:function(show){
			this.$.chart.toggleEmpty(show);
		},
		toggleLoading:function(status){
			if(status){
				this.showLoading();
			}else{
				this.hideLoading();
			}
			return this;
		},
		// 解析子表格的Condition配置，用于子表格过滤指标组
		parseSubsCondition: function(config){
			var c = config.get();
			var ret = [];
			var param = c.param;
			var condition = '';

			if(param && param.condition){
				// 先解析字符串
				condition = JSON.parse(param.condition);
				util.each(condition, function(item, idx){
					if(item && util.isObject(item)){
						for(var i in item){
							var key = i;
							if(key){
								if (key.slice(-3) === '_id'){
									ret.push(key.slice(0,-3));
								}else {
									ret.push(key);
								}
							}
						}
					}
				});
			}
			// 返回condition的key数组
			return ret;
		}
	});
	exports.period = PeriodChart;

	// 频次图表
	var Frequency = PeriodChart.extend({
		init:function(config){
			// 汇总子表格
			var overview_subgrid = config.param && config.param.overview_subgrid;
			this.$overview_subgrid = this.$overview_subgrid || {};
			if(overview_subgrid)
			{
				this.$overview_subgrid = {
					'get_all_info': 1,
					'ListAll':1,
					'showChildren':1,
					'overview_subgrid':1
				}
			}

			config = pubjs.conf(config, {
				"class":"M-chartAdv M-chartAdvMain"
				// 图表类型
				,"type":"line"
				// x轴要显示的字段
				,"label_field":"trend_key"
				// 图表x轴步长。
				,"xAxisSetp":6
				// 表格每页显示页数
				,"table_size":20
				// 数据接口
				,"url":"trend/frequency"
				,"url_table":"frequency/list"
				,"param": null
				,'reqType': 'websocket'

				// 图表配置
				,"chart":{
					// 'height': 600,
					'build': {
						xAxis: {
							labels: {
								step:1,
								rotation: -25,
								align: 'right'
							}
						},
						yAxis: [
							{opposite: false, min:0, title:{text:LANG('展示量')}},
							{opposite: true, min:0, title:{text:LANG('点击量')}}
						]
					},
					'series':[
						{y_axis:0,y_field:'impressions_0',label_field:'trend_key',text:LANG('展示量(1次)')},
						{y_axis:0,y_field:'impressions_1',label_field:'trend_key',text:LANG('展示量(2次)')},
						{y_axis:0,y_field:'impressions_2',label_field:'trend_key',text:LANG('展示量(3次)')},
						{y_axis:0,y_field:'impressions_3',label_field:'trend_key',text:LANG('展示量(4次)')},
						{y_axis:1,y_field:'clicks_0',label_field:'trend_key',text:LANG('点击量(1次)')},
						{y_axis:1,y_field:'clicks_1',label_field:'trend_key',text:LANG('点击量(2次)')},
						{y_axis:1,y_field:'clicks_2',label_field:'trend_key',text:LANG('点击量(3次)')},
						{y_axis:1,y_field:'clicks_3',label_field:'trend_key',text:LANG('点击量(4次)')}
					]
				}
				,'gridName': 'frequency'
			});

			this.$data = null;

			this.Super('init', arguments);

			config.set('param', util.extend(
					0,						// 覆盖复制
					config.get('param'),
					{
						"metrics": [		// 查询指标
							'impressions',
							'clicks'
						],
						"viewtb": 0,		// 时间粒度
						"noAmount": true,
						"no_limit": true
					},
					this.$overview_subgrid,
					pubjs.getDate()
				)
			);
		}
		,afterBuild:function(){
			var c = this.getConfig();

			this.append([
				// 日期控件
				'<div class="M-chartAdvDateBox" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				// 图表切换
				'<div class="M-chartAdvModeBox clear" pub-name="mode" pub-mod="@base/common/input.buttonGroup" />',
				// 刷新按钮
				'<div class="M-chartAdvRefreshBox">',
					'<button title="'+LANG('刷新')+'" class="refNormal">',
						'<i class="uk-icon-rotate-right"/>',
					'</button>',
				'</div>',
				// 时间粒度
				'<div class="M-chartAdvTimeBox" pub-name="time" pub-mod="@base/common/input.timeRange" />',
				// 趋势图
				'<div class="M-chartAdvChart pt30" pub-name="chart" pub-mod="@base/chart.line" />',
				// 表格
				'<div class="M-chartAdvGrid" pub-name="grid" pub-mod="@base/highGrid.base" />'
			].join(''));

			// 绑定按钮事件
			this.jq(this.$el.find('.M-chartAdvRefreshBox button'), "click", "eventRefreshClick");

			var config = {
				'mode': {
					"selected": 1, // 0 图，1 表
					"items":[LANG("图"),LANG("表")]
				},
				'time': {
					"selected": 0,
					'items': [LANG('小时'), LANG('天'), LANG('周'),LANG('月')]
				},
				'chart': $.extend({width: this.$el.width()}, c.chart),
				'grid': {
					url: c.url_table,
					param: util.extend(
						{
							viewtb: 0,
							condition: c.param.condition
						},
						this.$overview_subgrid
					),
					auto_load:false,
					cols: [
						{type:"id"},
						{name:'frequencyslot_name',text: LANG('名称')}
					],
					metrics: ["{front}","{cost}"],
					default_metrics : [
						'impressions','clicks','click_rate',
						'end_cpc','end_cpm','cost'
					],
					hasPager: true,
					hasSubGrid: false,
					hasRefresh: false,
					reqType: 'websocket',
					gridName: 'frequency',
					'hasSearch': false,
					'hasFilter': false,
					'hasDateRange': false
					// wrapperClass: 'G-frameBodyContainer'
				},
				'date': {
					'pos': 'bR',
					'broadcast': false
				}
			};

			this.buildFromTemplate(config);
		}
		,setData:function(data){
			this.$data = this._formatData(data.items);

			var type = +this.$.mode.getData();

			// 趋势图
			if(type === 0){
				var chart = this.$.chart;
				chart.setData(this.$data);
				return;
			}

			// 表格
			if(type === 1){
				this.$.grid.setData(this.$data);
				return;
			}
		}
		,_formatData: function(data){
			var list = [];
			for (var e in data) {
				var item = data[e];
				var value = {};
				for (var y = 0; y < item.length; y++) {
					if(!y){
						value['frequencyslot_name'] = item[y].frequencyslot_name;
						value['trend_key'] = item[y].trend_key;
						value['hour'] = item[y].hour;

					}
					value['clicks_'+y] = item[y].clicks;
					value['impressions_'+y] = item[y].impressions;
				}
				list.push(value)
			}

			return list;
		}
	});
	exports.frequency = Frequency;

	//首页对比图表
	var ComparisonChart = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"class":"M-chartAdv"

				// 数据接口
				,"metricsUrl":"account/todayCompare"
				,"trendUrl":"account/todayCompareTrend"
				,"param":{
					"metrics": []
					,"viewtb": 0
					,"no_limit": true
				}
				,'reqType': 'websocket'
				// 时间粒度
				,"viewtb":0
				// 默认展示指标
				,"defaultMetrics": ["cost","impressions","clicks","click_rate","cpm","cpc"]
				// 图表配置
				,"chart":{
					"height":470,
					"xField": {
						field: 'trend_key'       // X轴字段名称
						,format: null       // X轴格式化函数
					},
					"yField": [
						{						// 汇总数据
							"id": 'today',
							"text": LANG('今日') ,
							"field": 'today'
						},
						{						// 汇总数据
							"id": 'other',
							"text": LANG('对比') ,
							"field": 'other'
						}
					]
					// ,"colors": ["#1F5AA3","#333333"]
				}
				,"grid":1
				// 允许切换时间粒度
				,"allowChangeTimerange":true
				// 允许切换图表类型
				,"allowChangeType":false
				// 默认显示的指标
				// {text: LANG('展示量'),field: "impressions",label_field: 'trend_key'}
				,"defIndex":null
				// 支持的指标
				,"indexs":null
				// 图表类型
				,"type":"line"
				// 可添加的统计数据总量
				,"max":3
				// 折叠状态
				,"collapse":0
				// 是否已折叠
				,"hasCollapse":0
				// x轴要显示的字段
				,"label_field":"trend_key"
				// 图表x轴步长。
				,"xAxisSetp":6
				// 表格每页显示页数
				,"table_size":20
				// 是否显示标题
				,"hasTitle":true
				// 默认标题
				,"title":LANG("标题")
				// 是否有汇总
				,"hasTotal":false
				// 自动抓取数据
				,"autoLoad":true
				// 主判断键名
				,"key":"_id"
				// 请求conditions字段的配置
				// 当有多个要传递或传递的conditions与param中的type不同时使用
				// key代表condition，对应的值表示取数据中的某个字段
				// eg.{"user":"Id","status":"RunStatus"}
				,"conditions":null
				// 每个condition的后缀
				,"conditionSuffix":"_id"
				// 是否在参数中传递condition
				,"hasCondition":true
				,"tab":null// 指标分组配置
				,"overview": false // 是否查看汇总信息（get_all_info),图和表都要发这个参数
				,"metricsOptions": [] //指标配置
				,"vModel": {
					metricsData: [
						{
							'id': "cost",
							'name': LANG("消耗"),
							'today': 0.00,
							'other': 0.00,
							'unit':  pubjs.currUnit()
						},
						{
							'id': "impressions",
							'name': LANG("展示量"),
							'today': 0.00,
							'other': 0.00,
							'unit':  LANG("千次")
						},
						{
							'id': "clicks",
							'name': LANG("点击量"),
							'today': 0.00,
							'other': 0.00,
							'unit':  LANG("次")
						},
						{
							'id': "click_rate",
							'name': LANG("点击率"),
							'today': 0.00,
							'other': 0.00
						},
						{
							'id': "cpm",
							'name': "CPM",
							'today': 0.00,
							'other': 0.00,
							'unit':  pubjs.currUnit()
						},
						{
							'id': "cpc",
							'name': "CPC",
							'today': 0.00,
							'other': 0.00,
							'unit':  pubjs.currUnit()
						},
					]
				}
			});

			var c = config.get();

			// 图表类型
			this.$type = "line";

			// 当前模式:0图，1表
			this.$mode = 1;

			// 选择的日期
			this.$date = null;

			this.doms = {
				"index":null
				,"time":null
				,"collapse":null
				,"chart":null
				,"main":null
				// ,"refresh":null
				,"mode":null
				,"metrics":null
			}

			this.$collapse = c.collapse;

			this.$first = true;

			this.$yesterday = util.date('Y-m-d',util.today()- 86399);

			this.$selectedMetric = 'cost';

			this.$ownMetrics = pubjs.config('ownMetrics') || [];

			this.initConfig(c);

			this.Super('init', arguments);

			// 数据
			this.$data = {};
		}
		/**
		 * 获取图表支持的指标相关设定
		 * @param  {Object} labels 表格指标设定模块
		 * @return {Object}        模块实例
		 */
		,initConfig:function(c){
			var ownMetrics = this.$ownMetrics;
			if(!ownMetrics.length){
				pubjs.alert("没有查看权限");
				return false;
			}
			var defaultMetrics = c.defaultMetrics;
			var metricsData = c.vModel.metricsData;

			//若默认展示指标中包含无权限的指标，则剔除
			for(var i = 0;i < defaultMetrics.length;i++){
				if(ownMetrics.indexOf(defaultMetrics[i]) === -1){
					defaultMetrics.splice(i,1);
					i--;
				}
			}

			//通过默认展示指标确定vModle中渲染的指标
			for(var i = 0;i < metricsData.length;i++){
				if(defaultMetrics.indexOf(metricsData[i].id) === -1){
					metricsData.splice(i,1);
					i--;
				}
			}

			//通过默认展示指标确定vModle中渲染的指标
			//并设置指标下拉框的值
			for(var i = 0;i < metricsData.length;i++){
				if(defaultMetrics.indexOf(metricsData[i].id) === -1){
					metricsData.splice(i,1);
					i--;
				}
				c.metricsOptions.push({
					id: metricsData[i].id,
					name: metricsData[i].name
				})
			}
			return this;
		}
		,afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			if(!self.$ownMetrics.length){
				return false;
			}

			self.doms.main = $('<div class="M-chartAdvMain"></div>').appendTo(el);

			// 折叠功能
			if(c.hasCollapse){
				self.doms.collapse = $([
					'<div class="M-chartAdvCollapse">',
						'<div>',
							'<p data-close="0">',
								'<em class="triangle-top"></em>',
								'<b></b>',
								'<span></span>',
								'<i></i>',
							'</p>',
						'</div>',
					'</div>'
				].join('')).appendTo(el);
				self.doms.collapseBtn = self.doms.collapse.find("p:first");
				// self.toggleChart(!self.$collapse, true, true);
				self.jq(self.doms.collapseBtn,"click mouseenter mouseleave","eventToggleTrend");
			}else{
				self.buildChart(function() {
					self.load();
				});
			}

			return this;
		}
		,buildChart: function(callback){
			var conf = this.getConfig();
			var that = this;
			var cb = function() {
				that.switchMode(that.$mode);
				if (callback) {
					callback.call(that);
				}
			}

			if (this.$chartIsBuilded) {
				cb();
				return this;
			}
			this.$chartIsBuilded = true;

			// 时间选择器
			if(conf.allowChangeTimerange){
				this.doms.time = $([
					'<div class="M-chartAdvTimeBox">',
						'<span class = "mr15">' + LANG('今天') + '</span>',
						'<span class = "mr15">' + LANG('对比') + '</span>',
					'</div>'].join('')).appendTo(this.doms.main);

				this.create(
					"time"
					,date.datePickerNew
					,{
						"target": this.doms.time,
						"pos": "bR",
						"max": this.$yesterday
					}
				);
				this.$.time.setData(this.$yesterday);
			}

			// 指标数据展示
			this.doms.metrics = $([
				'<div class = "M-chartAdvMetricsPanel">',
					'<div class = "MetricsBox" v-for = "item in metricsData">',
						'<div class = "MetricsTitle">',
							'<span>',
								'{{item.name}}',
							'</span>',
							'<span class = "ml5" v-if = "item.unit !== undefined">',
								'({{item.unit}})',
							'</span>',
						'</div>',
						'<div class = "T_Metrics">',
							'{{item.today}}',
						'</div>',
						'<div class = "C_Metrics">',
							'{{item.other}}',
						'</div>',
					'</div>',
				'</div>'].join('')).appendTo(this.doms.main);

			// 下拉框
			if(conf.grid){
				//指标下拉框
				this.doms.mode = $('<div class="M-chartAdvModeBox"></div>').appendTo(this.doms.main);
				this.createDelay(
					"metricsDrop"
					,'@base/common/drop.drop'
					,{
						"options": this.getConfig().metricsOptions
						,"addClass": 'mr10 simple2'
						,"target": this.doms.mode
						,"width": 100
						,"value": 'cost'
						,"hasSearch": false
						,"autoFire": false
						,"panel_config": {
							"appendTo": "popup"
						}
					}
				);
				//图表切换下拉框
				this.createDelay(
					"typeDrop"
					,'@base/common/drop.drop'
					,{
						"options":[
							{
								'name': LANG('表格'),
								'id': 'grid'
							},
							{
								'name': LANG('曲线图'),
								'id': 'chart'
							}
						]
						,"addClass": 'simple2'
						,"target": this.doms.mode
						,"width": 100
						,"value": 'grid'
						,"hasSearch": false
						,"autoFire": false
						,"selected": this.$mode
						,"panel_config": {
							"appendTo": "popup"
						}
					}
				);
			}

			// 设定图表添加区域
			this.doms.chart = $('<div class="M-chartAdvChart"></div>').appendTo(this.doms.main);
			// 完成配置
			conf.chart.target = this.doms.chart;
			this.create("chart", echarts[this.$type], conf.chart);

			// 表格
			if(conf.grid){
				this.doms.grid = $('<div class="M-chartAdvGrid"></div>').appendTo(this.doms.main);
				this.create("grid", grid.base,{
					target: this.doms.grid,
					auto_load: true,
					cols: [
						{name:'trend_key',text: LANG('时段') ,width:200,align: 'center',sort: false},
						{name:'today', text: LANG('今天') ,width:300,align: 'center',sort: false},
						{name:'other', text: LANG('对比') ,width:300,align: 'center',sort: false}
					],
					hasPager: false,
					hasAmount: false,
					hasSubGrid: false,
					hasRefresh: false,
					hasTab: false,
					hasExport: false,
					reqType: 'websocket',
					gridName: 'period',
					wrapperClass: 'M-chartAdvGrid',
					formatData: function(data){
						return {'items': data && data.other && data.today};
					},
					'hasSearch': false,
					'hasFilter': false
				});
			}

			this.createDelay(true, function() {
				cb();
			});

			this.vm.mount();
			return this;
		}
		,onDropChange: function(ev){
			if(ev.name === "typeDrop"){
				switch (ev.param.id){
					case "chart":
						this.switchMode(0)
						break;
					case "grid":
						this.switchMode(1)
						break;
				}
			}
			if(ev.name === "metricsDrop"){
				this.$selectedMetric = ev.param.id;
			}
			this.load();
		}
		,onDateChange: function(ev){
			this.load();
			return false;
		}
		,load:function(param){
			var self = this;
			var c = this.getConfig();
			var trendParam = this.getParam();
			//设置总体指标的数据
			this.setMetricsData();

			// this.$.grid.showLoading();
			this.showLoading();
			this.$first = false;
			pubjs.mc.send(c.trendUrl,trendParam,this.onData.bind(this));
			if(this.$mode === 0){
				this.$.chart.resize();
			}
		}
		,onData:function(err, data){
			// this.$.grid.hideLoading();
			this.hideLoading();
			if(err){
				pubjs.alert(err.message);
				return false;
			}
			this.setData(data);
		}
		,getData:function(){
			return this.$data;
		}
		,setData:function(data){
			var c = this.getConfig();
			var self = this;
			var today = data.today;
			var other = data.other;
			var trend = [];

			for(var i = 0;i< other.items.length;i++){
				trend.push({
					trend_key: other.items[i].trend_key,
					today: this._formatData(today.items[i][this.$selectedMetric]),
					other: this._formatData(other.items[i][this.$selectedMetric])
				})
			}

			//表
			if(this.$mode){
				trend.unshift({
					trend_key: "汇总",
					today: this._formatData(today.amount[this.$selectedMetric]),
					other: this._formatData(other.amount[this.$selectedMetric])
				});

				this.$.grid.setData(trend);
				this.setColTitle();
			}
			//图
			else{
				util.each(trend,function(value,index){
					value.today = self._getNumberData(value.today);
					value.other = self._getNumberData(value.other);
				})
				this.$.chart.setData(trend);
			}
			return this;
		}
		//设置指标展示栏的数据
		,setMetricsData: function(){
			var self = this;
			var c = this.getConfig();
			var param = {
				begindate: this.$.time.getData(true),
				enddate: this.$.time.getData(true),
				metrics: c.defaultMetrics
			};

			pubjs.mc.send(c.metricsUrl, param, function(error,data){
				var today = data.today;
				var other = data.other;
				var metricsData = self.vm.$.metricsData;

				util.each(today,function(value,index){
					for(var i =0;i < metricsData.length;i++){
						if(index === metricsData[i].id){
							metricsData[i].today = self._formatData(value,index);
						}
					}
				});

				util.each(other,function(value,index){
					for(var i =0;i < metricsData.length;i++){
						if(index === metricsData[i].id){
							metricsData[i].other = self._formatData(value,index);
						}
					}
				});
			});

			return this;
		}
		//设置表格标题
		,setColTitle: function(){
			var name = labels['config'][this.$selectedMetric].text;
			var compare =  this.$.time.getData();
			var con = this.doms.main;
			con.find("[data-col = 1]").children("span").text("今天" + " " + name);
			con.find("[data-col = 2]").children("span").text(compare + "  " + name);
		}
		,reset:function(){
			this.$mode = 0;
			this.$.time.setData(this.$yesterday);
			this.$.mode.setData(this.$mode);
			this.$.time.setData({
				begin: util.today() - 86399*7,
				end: util.today() - 86399
			});
			this.$.metricsDrop.reset();
			this.$.typeDrop.reset();
			this.$data = {};
			this.$.chart.reset();
		}
		,setParam:function(param,replace){
			var c = this.getConfig();
			if(param){
				if(replace){
					c.param = param;
				}else {
					$.extend(c.param, param);
				}
			}
			return this;
		}
		,getParam: function(){
			var c = this.getConfig();
			var param = c.param;

			param.begindate = this.$.time.getData(true);
			param.enddate =  this.$.time.getData(true);
			param.metrics = [this.$.metricsDrop.getValue(true).id];

			return param;
		}
		// 获取表格数据
		,buildGridData:function(){
			var c = this.getConfig();
			var list = [];
			var data = this.$data['amount'];

			for(var i = 0,l = (data && data.length || 0);i<l;i++){
				if(!this.$timeRange || i < c.table_size){
					list.push(data[i]);
				}else{
					break;
				}
			}
			data = null;
			return {'items': list};
		}
		// 切换显示图表，表格
		,switchMode:function(mode){
			var c = this.getConfig();
			if(mode !== undefined){
				this.$mode = parseInt(mode,10);
			}
			this.doms.chart.toggle(this.$mode === 0);
			this.doms.grid.toggle(this.$mode === 1);

			return this;
		}
		//监听窗口变化,resize统计图
		,onDocumentResize:function(){
			if(this.$mode === 0){
				this.$.chart.resize();
			}
		}
		/**
		 * 获取指定字段的数据
		 * @param  {Object}   data     数据对象
		 * @param  {String}   key      字段名
		 * @param  {Function} formater 格式化函数
		 * @return {Number}            获取的数据
		 * @private
		 */
		,_formatData:function(value,type){
			if(!type){
				type = this.$selectedMetric;
			}
			return format[labels['config'][type].format](value);
		}
		/**
		 * 将格式化后的数据转回图表能用的数字
		 * @param  {String} data 要处理的数据字符串
		 * @return {Number}      处理完的数据(处理过程中如果NaN则会当成0)
		 * @private
		 */
		,_getNumberData:function(data){
			data = ""+data;
			data = data.replace(/[^0-9\.]/g,"");
			data = parseFloat(data);
			data = isNaN(data)?0:data;
			return data;
		}

	});
    exports.comparison = ComparisonChart;

    //首页汇总图表
    var SummaryChart = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"class":"M-chartAdv"

				// 数据接口
				,"metricsUrl":"account/metricData"
				,"trendUrl":"account/metricDataTrend"
				,"param":{
					"metrics": [],	// 查询指标,默认为消耗
					"viewtb": 1,	// 时间粒度
					"no_limit": true
				}
				,'reqType': 'websocket'

				// 时间粒度
				,"viewtb":1
				// 默认展示指标
				,"defaultMetrics": ["cost","impressions","clicks","click_rate","cpm","cpc"]
				// 图表配置
				,"chart":{
					"height":470,
					// ,"width": "100%"
					"xField": {
						field: 'trend_key'       // X轴字段名称
						,format: null       // X轴格式化函数
					},
					"yField": [
						{						// 汇总数据
							"id": 'amount',
							"text": LANG('今日') ,
							"field": 'amount'
						}
					]
				}
				,"grid":1
				// 允许切换时间粒度
				,"allowChangeTimerange":true
				// 允许切换图表类型
				,"allowChangeType":false
				// 默认显示的指标
				// {text: LANG('展示量'),field: "impressions",label_field: 'trend_key'}
				,"defIndex":null
				// 支持的指标
				,"indexs":null
				// 图表类型
				,"type":"line"
				// 可添加的统计数据总量
				,"max":3
				// 折叠状态
				,"collapse":0
				// 是否已折叠
				,"hasCollapse":0
				// 表格每页显示页数
				,"table_size":20
				// 自动抓取数据
				,"autoLoad":true
				// 主判断键名
				,"key":"_id"
				// 请求conditions字段的配置
				// 当有多个要传递或传递的conditions与param中的type不同时使用
				// key代表condition，对应的值表示取数据中的某个字段
				// eg.{"user":"Id","status":"RunStatus"}
				,"conditions":null
				// 每个condition的后缀
				,"conditionSuffix":"_id"
				// 是否在参数中传递condition
				,"hasCondition":true
				,"tab":null// 指标分组配置
				,"overview": false // 是否查看汇总信息（get_all_info),图和表都要发这个参数
				,"metricsOptions": []
				,"vModel": { //T开头代表今日的指标，C开头代表对比的指标
					"metricsData": [
						{
							'id': "cost",
							'name': LANG("消耗"),
							'amount': null,
							'unit':  pubjs.currUnit()
						},
						{
							'id': "impressions",
							'name': LANG("展示量"),
							'amount': null,
							'unit': "千次"
						},
						{
							'id': "clicks",
							'name': LANG("点击量"),
							'amount': null,
							'unit': "次"
						},
						{
							'id': "click_rate",
							'name': LANG("点击率"),
							'amount': null
						},
						{
							'id': "cpm",
							'name': "CPM",
							'amount': null,
							'unit':  pubjs.currUnit()
						},
						{
							'id': "cpc",
							'name': "CPC",
							'amount': null,
							'unit':  pubjs.currUnit()
						},
					]
				}
			});

			var c = config.get();

			// 选择的日期
			this.$date = "最近7天";

			// 加载状态
			this.$loading = false;

			// 图表类型
			this.$type = c.type !== "advChart" ? c.type : "line";

			// 时间粒度
			this.$timeRange = c.viewtb;

			// 添加的趋势数量
			this.$serieNum = 0;
			this.$serieIndex = 0;

			// 当前模式:0图，1表
			this.$mode = 1;

			this.doms = {
				"index":null
				,"time":null
				,"collapse":null
				,"chart":null
				,"main":null
				// ,"refresh":null
				,"mode":null
				,"metrics":null
			}

			this.$collapse = c.collapse;

			//默认指标为消耗
			this.$selectedMetric = 'cost';

			this.initConfig(c);

			this.Super('init', arguments);

			// 数据
			this.$data = {};
		} /**
		 * 获取图表支持的指标相关设定
		 * @param  {Object} labels 表格指标设定模块
		 * @return {Object}        模块实例
		 */
		,initConfig:function(c){
			var ownMetrics = pubjs.config('ownMetrics');
			if(!ownMetrics.length){
				pubjs.alert("没有查看权限");
				return false;
			}
			var defaultMetrics = c.defaultMetrics;
			var metricsData = c.vModel.metricsData;

			//若默认展示指标中包含无权限的指标，则剔除
			for(var i = 0;i < defaultMetrics.length;i++){
				if(ownMetrics.indexOf(defaultMetrics[i]) === -1){
					defaultMetrics.splice(i,1);
					i--;
				}
			}

			//通过默认展示指标确定vModle中渲染的指标
			for(var i = 0;i < metricsData.length;i++){
				if(defaultMetrics.indexOf(metricsData[i].id) === -1){
					metricsData.splice(i,1);
					i--;
				}
			}

			//通过默认展示指标确定vModle中渲染的指标
			//并设置指标下拉框的值
			for(var i = 0;i < metricsData.length;i++){
				if(defaultMetrics.indexOf(metricsData[i].id) === -1){
					metricsData.splice(i,1);
					i--;
				}
				c.metricsOptions.push({
					id: metricsData[i].id,
					name: metricsData[i].name
				})
			}

			return this;
		}
		,afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			self.doms.main = $('<div class="M-chartAdvMain"></div>').appendTo(el);

			// 折叠功能
			if(c.hasCollapse){
				self.doms.collapse = $([
					'<div class="M-chartAdvCollapse">',
						'<div>',
							'<p data-close="0">',
								'<em class="triangle-top"></em>',
								'<b></b>',
								'<span></span>',
								'<i></i>',
							'</p>',
						'</div>',
					'</div>'
				].join('')).appendTo(el);
				self.doms.collapseBtn = self.doms.collapse.find("p:first");
				// self.toggleChart(!self.$collapse, true, true);
				self.jq(self.doms.collapseBtn,"click mouseenter mouseleave","eventToggleTrend");
			}else{
				self.buildChart(function() {
					self.load();
				});
			}

			return this;
		}
		,buildChart: function(callback){
			var conf = this.getConfig();
			var that = this;
			var cb = function() {
				that.switchMode(that.$mode);
				if (callback) {
					callback.call(that);
				}
			}

			if (this.$chartIsBuilded) {
				cb();
				return this;
			}
			this.$chartIsBuilded = true;

			// 时间选择器
			if(conf.allowChangeTimerange){
				this.doms.time = $('<div class="M-chartAdvTimeBox"></div>').appendTo(this.doms.main);

				this.create(
					"time"
					,date.dateRangeNew
					,{
						"target": this.doms.time,
						"pos": "bR",
						"max": this.$yesterday,
						"buttons": [
							{
								"text":LANG("最近7天"),
								"begin":-7,
								"end":-1,
								"type":"latestSeven"
							},
							{
								"text":LANG("最近30天"),
								"begin":-30,
								"end":-1,
								"type":"latestThirty"
							},
							{
								"text":LANG("本月"),
								"begin": -(new Date()).getDate()+1,
								"end": -1,
								// 特殊指定操作类型
								"type":"currentMonth"
							},
							{
								"text":LANG("上一时段"),
								"type":"prevDay"
							},
							{
								"text":LANG("下一时段"),
								"type":"nextDay"
							},
							{
								"text":LANG("不限"),
								"type":"noLimit"
							}
						]
					}
				);

				var begin = util.today() - 86399*7;
				var end = util.today() - 86399;
				//默认为最近一个星期
				this.$.time.setData({
					begin: begin,
					end: end
				});

				this.$date = util.date('Y-m-d',begin) + " 至 " + util.date('Y-m-d',end);
			}
			// 指标数据展示
			this.doms.metrics = $([
				'<div class = "M-chartAdvMetricsPanel">',
					'<div class = "MetricsBox" v-for="item in metricsData">',
						'<div class = "MetricsTitle">',
							'<span>',
								'{{item.name}}',
							'</span>',
							'<span class = "ml5" v-if = "item.unit !== undefined">',
								'({{item.unit}})',
							'</span>',
						'</div>',
						'<div class = "T_Metrics">',
							'{{item.amount}}',
						'</div>',
					'</div>',
				'</div>'].join('')).appendTo(this.doms.main);

			this.vm.mount();

			// 下拉框
			if(conf.grid){
				//指标下拉框
				this.doms.mode = $('<div class="M-chartAdvModeBox"></div>').appendTo(this.doms.main);
				this.createDelay(
					"metricsDrop"
					,"@base/common/drop.drop"
					,{
						"options": this.getConfig().metricsOptions
						,"addClass": 'mr10 simple2'
						,"target": this.doms.mode
						,"width": 100
						,"value": 'cost'
						,"hasSearch": false
						,"selected": this.$mode
						,"autoFire": false
						,"panel_config": {
							"appendTo": "popup"
						}
					}
				);
				//图表切换下拉框
				this.createDelay(
					"typeDrop"
					,"@base/common/drop.drop"
					,{
						"options":[
							{
								'name': LANG('表格'),
								'id': 'grid'
							},
							{
								'name': LANG('曲线图'),
								'id': 'chart'
							}
						]
						,"addClass": 'simple2'
						,"target": this.doms.mode
						,"width": 100
						,"value": 'grid'
						,"hasSearch": false
						,"selected": this.$mode
						,"autoFire": false
						,"panel_config": {
							"appendTo": "popup"
						}
					}
				);
			}

			// 设定图表添加区域
			this.doms.chart = $('<div class="M-chartAdvChart"></div>').appendTo(this.doms.main);
			// 完成配置
			conf.chart.target = this.doms.chart;
			this.create("chart", echarts[this.$type], conf.chart);

			// 表格
			if(conf.grid){
				this.doms.grid = $('<div class="M-chartAdvGrid"></div>').appendTo(this.doms.main);
				this.createDelay("grid", '@base/grid.base',{
					target: this.doms.grid,
					auto_load: true,
					cols: [
						{name:'trend_key',text: LANG('日期'),width: 300,align: 'center',sort: false},
						{name:'amount',text: LANG('数据'),width: 500,align: 'center',sort: false}
					],
					hasPager: false,
					hasAmount: false,
					hasSubGrid: false,
					hasRefresh: false,
					hasTab: false,
					hasExport: false,
					hasSearch: false,
					hasFilter: false,
					reqType: 'websocket',
					gridName: 'period',
					wrapperClass: 'M-chartAdvGrid',
					formatData: function(data){
						return {'items': data && data.amount};
					}
				});
			}

			this.createDelay(true, function() {
				cb();
			});
			return this;
		}
		,onDropChange: function(ev){
			if(ev.name === "typeDrop"){
				switch (ev.param.id){
					case "chart":
						this.switchMode(0)
						break;
					case "grid":
						this.switchMode(1)
						break;
				}
			}
			if(ev.name === "metricsDrop"){
				this.$selectedMetric = ev.param.id;
			}
			this.load();
		}
		,load:function(param){
			var self = this;
			var c = this.getConfig();
			var trendParam = this.getParam();

			this.setMetricsData();
			this.showLoading();
			this.$first = false;
			pubjs.mc.send(c.trendUrl,trendParam,this.onData.bind(this));
			if(this.$mode === 0){
				this.$.chart.resize();
			}
		}
		,onData:function(err, data){
			this.hideLoading();

			if(err){
				pubjs.alert(err.message);
				return false;
			}
			this.setData(data);
		}
		,getData:function(){
			return this.$data;
		}
		,setData:function(data){
			var c = this.getConfig();
			var self = this;
			var items = data.items;
			var other = data.other;
			var trend = [];

			util.each(data.items,function(value,index){
				trend.push({
					trend_key: value.trend_key,
					amount: self._formatData(value[self.$selectedMetric])
				})
			});
			//表
			if(this.$mode){
				trend.reverse();
				trend.unshift({
					trend_key: "汇总",
					amount: this._formatData(data.amount[this.$selectedMetric])
				});

				this.$.grid.setData(trend);
				this.setColTitle();
			}
			//图
			else{
				var param = [{
					text: this.$date,
					field: "amount"
				}];

				this.$.chart.setConfig("yField",param);

				util.each(trend,function(value,index){
					value.amount = self._getNumberData(value.amount);
				})

				this.$.chart.setData(trend);
			}
			return this;
		}
		//设置表格标题
		,setColTitle: function(){
			var name = labels['config'][this.$selectedMetric].text;

			this.doms.main.find("[data-col = 1]").children("span").text(name);
		}
		//设置指标展示栏的数据
		,setMetricsData: function(){
			var self = this;
			var c = this.getConfig();
			var date = this.$.time.getData(true);
			var param = {
				begindate: date.begin,
				enddate: date.end,
				metrics: c.defaultMetrics
			};

			pubjs.mc.send(c.metricsUrl, param, function(error,data){
				var metricsData = self.vm.$.metricsData;
				util.each(data,function(value,index){
					for(var i =0;i < metricsData.length;i++){
						if(index === metricsData[i].id){
							metricsData[i].amount = self._formatData(value,index);
						}
					}
				});
			});

			return this;
		}
		,reset:function(){
			this.$mode = 0;
			this.$.mode.setData(this.$mode);
			this.$.time.setData({
				begin: util.today() - 86399*7,
				end: util.today() - 86399
			});
			this.$.metricsDrop.reset();
			this.$.typeDrop.reset();
			this.$data = {};
			this.$.chart.reset();
		}
		,setParam:function(param,replace){
			var c = this.getConfig();
			if(param){
				if(replace){
					c.param = param;
				}else {
					$.extend(c.param, param);
				}
			}
			return this;
		}
		,getParam: function(){
			var c = this.getConfig();
			var param = c.param;
			var date = this.$.time.getData(true);
			param.begindate = date.begin;
			param.enddate =  date.end;
			param.metrics = [this.$.metricsDrop.getValue(true).id];
			return param;
		}
		// 获取表格数据
		,buildGridData:function(){
			var c = this.getConfig();
			var list = [];
			var data = this.$data['amount'];

			for(var i = 0,l = (data && data.length || 0);i<l;i++){
				if(!this.$timeRange || i < c.table_size){
					list.push(data[i]);
				}else{
					break;
				}
			}
			data = null;
			return {'items': list};
		}
		// 切换显示图表，表格
		,switchMode:function(mode){
			var c = this.getConfig();
			if(mode !== undefined){
				this.$mode = parseInt(mode,10);
			}
			this.doms.chart.toggle(this.$mode === 0);
			this.doms.grid.toggle(this.$mode === 1);

			return this;
		}
		,onDateRangeChange:function(ev){
			var param = ev.param;
			this.$date = param.begin + " 至 " + param.end;
			this.load();
			return false;
		}
		//监听窗口变化,resize统计图
		,onDocumentResize:function(){
			if(this.$mode === 0){
				this.$.chart.resize();
			}
		}
		,_formatData:function(value,type){
			if(!type){
				type = this.$selectedMetric;
			}
			return format[labels['config'][type].format](value);
		}
		/**
		 * 将格式化后的数据转回图表能用的数字
		 * @param  {String} data 要处理的数据字符串
		 * @return {Number}      处理完的数据(处理过程中如果NaN则会当成0)
		 * @private
		 */
		,_getNumberData:function(data){
			data = ""+data;
			data = data.replace(/[^0-9\.]/g,"");
			data = parseFloat(data);
			data = isNaN(data)?0:data;
			return data;
		}
	});
    exports.summary = SummaryChart;
});